package cn.px.service.store.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import cn.px.common.bean.AbstractPageResultBean;
import cn.px.common.exception.BusinessException;
import cn.px.common.util.IdGeneratorUtils;
import cn.px.common.util.StringUtils;
import cn.px.dao.bean.MyPage;
import cn.px.dao.dto.sqarepartmanage.SpareTypeDTO;
import cn.px.dao.dto.store.StoreMonthReportDTO;
import cn.px.dao.entity.sqarepartmanage.SpareType;
import cn.px.dao.entity.store.Store;
import cn.px.dao.entity.store.StoreMonthReport;
import cn.px.dao.entity.upms.ScheduleJobLog;
import cn.px.dao.entity.upms.SysDept;
import cn.px.dao.entity.upms.SysUser;
import cn.px.dao.mapper.store.StoreMapper;
import cn.px.dao.mapper.store.StoreMonthReportMapper;
import cn.px.dao.mapper.upms.ScheduleJobLogMapper;
import cn.px.dao.mapper.upms.SysDeptMapper;
import cn.px.dao.mapper.upms.SysUserMapper;
import cn.px.service.base.impl.BaseServiceImpl;
import cn.px.service.sqarepartmanage.SpareTypeService;
import cn.px.service.store.StoreMonthReportService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.List;

/**
 * @Description 仓库信息 service 实现类
 * @author 品讯科技
 * @date 2024-08
 * @Version Copyright (c) 2020,北京乾元坤和科技有限公司 All rights reserved.
 */
@AllArgsConstructor
@Service("storeMonthReportService")
public class StoreMonthReportServiceImpl extends BaseServiceImpl<StoreMonthReportMapper, StoreMonthReport, StoreMonthReportDTO> implements StoreMonthReportService {
    private StoreMapper storeMapper;
    private SysUserMapper sysUserMapper;
    private SysDeptMapper sysDeptMapper;
    private SpareTypeService spareTypeService;
    private ScheduleJobLogMapper ScheduleJobLogMapper;
    /**
     * 每月1号凌晨1分开始统计，统计当前库存总额，统计
     */
    @Override
    public void genTask() {

        // 新建记录：获取年月和月份,需要提前一个月,因为自动启动时间是每月1号生成上个月的
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime lastDateTime = now.minusMonths(1);
        LocalDateTime preDateTime = lastDateTime.minusMonths(1);
        int year = lastDateTime.getYear();
        int month = lastDateTime.getMonthValue();
        //获取月的第一天0时0分0秒
        LocalDateTime nowfirstDay = now.with(TemporalAdjusters.firstDayOfMonth())
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);
        //获取月的最后一天的23点59分59秒
        LocalDateTime nowlastDay = now.with(TemporalAdjusters.lastDayOfMonth())
                .withHour(23)
                .withMinute(59)
                .withSecond(59);
        // 检查是否已经生成过, 每月只能有一次
        Weekend<ScheduleJobLog> detailWeekend = new Weekend<>(ScheduleJobLog.class);
        detailWeekend.weekendCriteria().andEqualTo(ScheduleJobLog::getBeanName, "storeMonthReportTask")
                .andEqualTo(ScheduleJobLog::getMethodName, "genStoreMonthReportTask")
                .andBetween(ScheduleJobLog::getCreatedTime, nowfirstDay, nowlastDay )
                .andEqualTo(ScheduleJobLog::getStatus, 0 );
        int count = ScheduleJobLogMapper.selectCountByExample(detailWeekend);
        if(count > 0){
            throw new BusinessException("此月份已经执行成功过，请等下个月生成");
        }

        //获取月的第一天0时0分0秒
        LocalDateTime firstDay = lastDateTime.with(TemporalAdjusters.firstDayOfMonth())
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);
        //获取月的最后一天的23点59分59秒
        LocalDateTime lastDay = lastDateTime.with(TemporalAdjusters.lastDayOfMonth())
                .withHour(23)
                .withMinute(59)
                .withSecond(59);

        // 查询数据
        List<Store> storeList = storeMapper.selectAll();
        List<SysUser> userList = sysUserMapper.selectAll();
        SpareTypeDTO spareTypeDTO = new SpareTypeDTO();
        List<SysDept> sysDeptList = sysDeptMapper.selectAll();
        spareTypeDTO.setFilter(1);
        List<SpareType> spareTypeList = spareTypeService.getModelListByDTO(spareTypeDTO);

        // 选择上个月的数据更新到这个余额
        int preYear = preDateTime.getYear();
        int preMonth = preDateTime.getMonthValue();
        Weekend<StoreMonthReport> weekend = new Weekend<>(StoreMonthReport.class);
        weekend.weekendCriteria().andEqualTo(StoreMonthReport::getYear, preYear)
                .andEqualTo(StoreMonthReport::getMonth, preMonth);
        List<StoreMonthReport> preList = mapper.selectByExample(weekend);

        // 统计一级类别
        List<StoreMonthReport> list = mapper.selectStoreMonthReportList();

        // 统计出入库总额
        StoreMonthReportDTO dto = new StoreMonthReportDTO();
        dto.setCreatedTimeStart(firstDay);
        dto.setCreatedTimeEnd(lastDay);
        List<StoreMonthReport> inList = mapper.selectInStoreMonthReportList(dto);
        List<StoreMonthReport> outList = mapper.selectOutStoreMonthReportList(dto);
        if(!CollectionUtils.isEmpty(list)){

            for(StoreMonthReport store:list){
                System.out.println( "第几个：" + store.getStoreId());
                store.setId(IdGeneratorUtils.getObjectId());
                store.setMonth(month);
                store.setYear(year);
                store.setCreatedTime(lastDateTime);
                store.setType(1);

                if(!CollectionUtils.isEmpty(preList)){
                    boolean find = false;
                    for(StoreMonthReport pre:preList){
                        if( store.getStoreId().equals(pre.getStoreId()) && store.getSpareTypeId().equals(pre.getSpareTypeId())){
                            store.setLastMonthAccount(pre.getCurrentMonthAccount());
                            find = true;
                            break;
                        }
                    }
                    if(!find){
                        store.setLastMonthAccount(new BigDecimal(0));
                    }
                }else{
                    store.setLastMonthAccount(new BigDecimal(0));
                }
                for(Store s:storeList){
                    if(store.getStoreId().equals(s.getId())){
                        store.setStoreName(s.getName());
                        for(SysUser user:userList){
                            if(store.getUserId().equals(user.getUserId())){
                                store.setCreatedUserId(store.getUserId());
                                store.setCreatedUserName(user.getRealName());
                                break;
                            }
                        }
                        break;
                    }
                }
                for(SysDept sysDept:sysDeptList){
                    System.out.println( "部门：" + sysDept.getName());
                    if(store.getUseCompany().equals(sysDept.getDeptId())){
                        store.setUseCompanyName(sysDept.getName());
                    }
                    if(StringUtils.isNotBlank(store.getUseProject()) && store.getUseProject().equals(sysDept.getDeptId())){
                        store.setUseProjectName(sysDept.getName());
                    }
                }
                for(SpareType type:spareTypeList){
                    System.out.println( "类型：" + type.getName());
                    if(store.getSpareTypeId().equals(type.getId())){
                        store.setSpareTypeName(type.getName());
                        break;
                    }
                }
                for(StoreMonthReport inStore:inList){
                    if(store.getStoreId().equals(inStore.getStoreId()) && store.getSpareTypeId().equals(inStore.getSpareTypeId())){
                        store.setInStoreAccount(inStore.getInStoreAccount());
                        break;
                    }
                }
                for(StoreMonthReport outStore:outList){
                    if(store.getStoreId().equals(outStore.getStoreId()) && store.getSpareTypeId().equals(outStore.getSpareTypeId())){
                        store.setOutStoreAccount(outStore.getOutStoreAccount());
                        break;
                    }
                }
            }
            list.forEach(item -> {
                System.out.println(item.toString());
            });
            mapper.insertListforComplex(list);
        }
    }

    @Override
    public AbstractPageResultBean<StoreMonthReport> selectPageList(StoreMonthReportDTO storeDTO, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new MyPage(mapper.selectList(storeDTO));
    }
}
